import { Track } from '@/core/track'
import {
  onMounted,
  onUnmounted,
  computed,
  reactive,
  readonly,
  ref,
  Ref,
  ComputedRef,
} from 'vue'
import { logger, timeline } from '@/instance'

export type StoryboardComposition = {
  currentTime: Ref<number>
  updateCurrentTime: (x: number) => void
  duration: Ref<number>
  storyboard: ComputedRef<Track>
}

export function useTimeline(): StoryboardComposition {
  const currentTime = ref(0) // export need wrap readonly
  const updateCurrentTime = (val: number) => {
    timeline.currentTime = val
    logger.log('composables/storyboard', 'updateCurrentTime', val)
  }
  const handleTimeUpdate = () => {
    currentTime.value = timeline.currentTime
    logger.log('composables/storyboard', 'handleTimeUpdate', timeline)
  }

  const duration = ref(0)
  const handleDurationChange = () => {
    duration.value = timeline.duration
    logger.log('composables/storyboard', 'handleDurationChange', timeline)
  }
  onMounted(() => {
    timeline.on('timeupdate', handleTimeUpdate)
    timeline.on('durationchange', handleDurationChange)
  })

  const storyboard = computed(() => {
    return reactive(timeline.tracks[0]) as Track
  })

  onUnmounted(() => {
    timeline.off('timeupdate', handleTimeUpdate)
    timeline.off('durationchange', handleDurationChange)
  })
  return {
    currentTime: readonly(currentTime),
    updateCurrentTime,
    duration: readonly(duration),
    storyboard,
  }
}
